package com.company.Thread.JUC;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

public class SemaphoreMain {
    static Semaphore semaphore;

    public static void main(String[] args) throws InterruptedException {
        AtomicInteger number = new AtomicInteger(0);       // 客人数量
        // 手牌数量，限制请求数量
        semaphore = new Semaphore(24);
        ExecutorService executorService = Executors.newFixedThreadPool(24);
        IntStream.range(0, 120).forEach(i -> executorService.execute(() -> {
            try {
                number.incrementAndGet();
                String vipNo = "vip-00" + i;
                semaphore.acquire(); // 获取令牌
                service(vipNo);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 释放令牌
                try {
                    Thread.sleep(10000);
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }));

        Thread.sleep(30000);
        System.out.println(number.get());
    }

    // 限流 控制5个线程 同时访问
    public static void service(String vipNo) throws InterruptedException {
        System.out.println("楼上出来迎接贵宾一位，贵宾编号" + vipNo + "，...");
        Thread.sleep(new Random().nextInt(3000));
        System.out.println("欢送贵宾出门，贵宾编号" + vipNo);
    }

}
